/* @flow */

import {  isDef } from '../../../util/index'

export default {
  create (_, vnode) {
    registerRef(vnode)
  },
  update (oldVnode, vnode) {
    if (oldVnode.data.ref !== vnode.data.ref) {
      registerRef(oldVnode, true)
      registerRef(vnode)
    }
  },
  destroy (vnode) {
    registerRef(vnode, true)
  }
}

export function registerRef (vnode) {
  const key = vnode.data.ref
  if (!isDef(key)) return
  const vm = vnode.context
  const ref = vnode.componentInstance || vnode.elm
  const refs = vm.$refs
  refs[key] = ref
}
